<template>
    <div class="main">
        <el-row>
            <el-col>
                <el-form :model="search" :inline="true">
                    <el-form-item>
                        <el-input v-model="search.name" placeholder="名称"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-select v-model="search.isPay" clearable placeholder="免费">
                            <el-option key="1" label="是" value="true" />
                            <el-option key="2" label="否" value="false" />
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="loadData" type="primary">搜索</el-button>
                        <el-button @click="resetSearch">重置</el-button>
                        <el-button @click="openBookAdd" type="primary">新增</el-button>
                        <el-button @click="exportWord" type="primary">导出</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>
        <el-row style="height: calc(100% - 0px);">
            <el-table height="100%" :data="dataList" border style="width: 100%;" :row-key="getRowKey" ref="singleTable"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" :reserve-selection="true" />
                <el-table-column type="expand">
                    <template #default="scope">
                        <div m="4">
                            <div>{{ scope.row.descs }}</div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="code" label="编号" min-width="100">
                    <template #default="scope">
                        <el-link type="primary" @click="selectAndUpdate(scope.row)">
                            {{ scope.row.code }}
                        </el-link>
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="名称" min-width="100" show-overflow-tooltip>
                    <template #default="scope">
                        {{ scope.row.name }}
                    </template>
                </el-table-column>
                <el-table-column prop="downurl" label="下载地址" min-width="140" show-overflow-tooltip />
                <el-table-column prop="categoryId" label="类型" min-width="60" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="isHot" label="推荐">
                    <template #default="scope">
                        {{ scope.row.isHot ? '是' : '否' }}
                    </template>
                </el-table-column>
                <el-table-column prop="money" label="费用（元）" />
                <el-table-column prop="discount" label="折扣" />
                <el-table-column prop="isPay" label="免费">
                    <template #default="scope">
                        {{ scope.row.isPay ? '是' : '否' }}
                    </template>
                </el-table-column>
                <el-table-column prop="newPrice" label="限时特价" />
                <el-table-column prop="descs" label="描述" min-width="140" show-overflow-tooltip />
                <el-table-column prop="isShow" label="展示">
                    <template #default="scope">
                        {{ scope.row.isShow ? '是' : '否' }}
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-link type="primary" @click="openChapterDialog(scope.row)">内容管理</el-link>
                    </template>
                </el-table-column>
            </el-table>
            <div style="display: flex;width: 100%;justify-content: center;">
                <el-pagination small v-model:current-page.sync="page" v-model:page-size="pageSize"
                    :page-sizes="[1, 10, 20, 30, 50]" background layout="total, sizes, prev, pager, next, jumper"
                    :total="total" @size-change="loadData" @current-change="loadData" />
            </div>
        </el-row>
    </div>
    <!-- 新增 -->
    <el-dialog v-model="bookDialog" title="add" width="80%" :align-center="true" @closed="closedBookDialog">
        <template #header>
            <span slot="title" class="dialogTitle1">新增</span>
        </template>
        <el-form :model="book" :rules="bookRefRules" ref="BookRef" label-width="110" label-position="right"
            class="demo-ruleForm">
            <div class="el-dialog-div">
                <el-row style="height: 100%;">
                    <el-col :span="17" style="height: 720px;overflow-y: auto;">
                        <el-row>
                            <el-col>
                                <el-form-item prop="name" label="名称">
                                    <el-input v-model="book.name" placeholder="名称"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col>
                                <el-form-item prop="downurl" label="下载地址">
                                    <el-input v-model="book.downurl" placeholder="下载地址"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col>
                                <el-form-item prop="imageUrl" label="封面">
                                    <el-upload class="avatar-uploader"
                                        action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
                                        :show-file-list="false">
                                        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                                        <el-icon v-else class="avatar-uploader-icon">
                                            <Plus />
                                        </el-icon>
                                    </el-upload>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="8">
                                <el-form-item prop="isHot" label="是否推荐">
                                    <el-radio-group v-model="book.isHot">
                                        <el-radio :label="true">是</el-radio>
                                        <el-radio :label="false">否</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item prop="isShow" label="是否对外显示">
                                    <el-radio-group v-model="book.isShow">
                                        <el-radio :label="true">是</el-radio>
                                        <el-radio :label="false">否</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item prop="isPay" label="限时免费">
                                    <el-radio-group v-model="book.isPay">
                                        <el-radio :label="true">是</el-radio>
                                        <el-radio :label="false">否</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>

                            <el-col :span="8">
                                <el-form-item prop="categoryId" label="类别">
                                    <el-select v-model="book.categoryId" class="m-2" placeholder="Select">
                                        <el-option :key="1" label="JAVA" :value="1" />
                                        <el-option :key="2" label="视频" :value="2" />
                                        <el-option :key="3" label="文档" :value="3" />
                                        <el-option :key="4" label="HTML+CSS" :value="4" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item prop="money" label="费用">
                                    <el-input-number v-model="book.money" :precision="2" :step="0.1" :min="0"
                                        placeholder="费用" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item prop="discount" label="折扣">
                                    <el-input-number v-model="book.discount" :min="0" :max="10" :precision="1" :step="0.1"
                                        controls-position="right" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item prop="sort" label="排序">
                                    <el-input v-model="book.sort" placeholder="排序"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col>
                                <el-form-item prop="descs" label="简介">
                                    <el-input type="textarea" :autosize="{ minRows: 10 }" v-model="book.descs"
                                        placeholder="描述"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-col>
                    <el-col :span="6" :offset="1" style="height: 100%;">
                        <span class="dialogTitle1 d-flex justify-content-between align-items-center">
                            <span>列表</span>
                            <el-link type="primary" @click="addBookChapter">新增</el-link>
                        </span>
                        <div style="height: 100%;margin-top: 5px;">
                            <ul class="list-group list-group-flush scopeCss"
                                style="height: calc(100% - 10px) ;overflow-y: auto;border: 0.5px dotted  rgba(71, 71, 71, 0.541);">
                                <li class="list-group-item d-flex justify-content-between align-items-center curos"
                                    v-for="(item, index) in book.chapterList" :key="index">
                                    <span class="text-secondary" v-show="!item.editStatus">
                                        {{ item.name }}
                                    </span>
                                    <div class="d-flex justify-content-between">
                                        <el-input v-show="item.editStatus" v-model="item.name" style="width: 75%;"
                                            placeholder="标题"></el-input>
                                        <el-input-number v-show="item.editStatus" controls-position="right"
                                            v-model="item.sort" style="width: 25%;font-size: 12px;"
                                            placeholder="排序"></el-input-number>
                                    </div>
                                    <div class="d-flex justify-content-between">
                                        <el-link type="primary" v-show="!item.editStatus"
                                            @click="item.editStatus = true"><el-icon>
                                                <Edit />
                                            </el-icon></el-link>
                                        <el-link type="primary" v-show="item.editStatus"
                                            @click="item.editStatus = false"><el-icon><Select /></el-icon></el-link>
                                        <el-link type="primary" v-show="item.name"
                                            @click="removeChapter(item, index)"><el-icon>
                                                <CloseBold />
                                            </el-icon></el-link>
                                    </div>
                                </li>
                            </ul>
                        </div>
                    </el-col>
                </el-row>
            </div>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="closeBookDialog">取消</el-button>
                <el-button :loading="loadingStatus" @click="saveBook" type="primary">确认</el-button>
            </span>
        </template>
    </el-dialog>

    <!-- 章节内容管理 -->
    <el-dialog v-model="chapterContentDialog" title="add" width="80%" :align-center="true" style="height: 650px;">
        <template #header>
            <span slot="title" class="dialogTitle1">管理</span>
        </template>
        <div style="display: flex;flex-direction: row;height: 60vh;">
            <div class="leftChapter" style="width: 210px;">
                <span class="dialogTitle1 d-flex justify-content-between align-items-center">
                    <span>列表</span>
                    <el-link type="primary" @click="addBookChapter">新增</el-link>
                </span>
                <div class="scopeCss" style="margin-top: 5px;height: 100%;overflow-y: auto;">
                    <ul class="list-group list-group-flush scopeCss" style="border: 0.5px dotted  rgba(71, 71, 71, 0.541);">
                        <li class="list-group-item d-flex justify-content-between align-items-center curos"
                            v-for="(item, index) in book.chapterList" :key="index" @click="getChapterCotnent(item)">
                            <span class="text-secondary" v-show="!item.editStatus">
                                {{ item.name }}
                            </span>
                            <div class="d-flex justify-content-between">
                                <el-input v-show="item.editStatus" v-model="item.name" placeholder="标题"></el-input>
                            </div>
                            <div class="d-flex justify-content-between">
                                <el-link type="primary" v-show="!item.editStatus"
                                    @click.stop="item.editStatus = true"><el-icon>
                                        <Edit />
                                    </el-icon></el-link>
                                <el-link type="primary" v-show="item.editStatus"
                                    @click="saveChapter(item)"><el-icon><Select /></el-icon></el-link>
                                <el-link type="primary" v-show="item.name" @click="removeChapter2(item, index)"><el-icon>
                                        <CloseBold />
                                    </el-icon></el-link>
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
            <div class="rightChapter" style="width: calc(100% - 220px);margin-left: 20px;height: 100%;">
                <span class="dialogTitle1 d-flex justify-content-between align-items-center">
                    <span>内容</span>
                </span>
                <div style="height: calc(100% - 60px) ;">
                    <v-md-editor @upload-image="handleUploadImage" :disabled-menus="[]" v-model="content.content"
                        height="100%"></v-md-editor>
                </div>
                <div class="d-flex justify-content-end align-items-center" style="margin-top: 5px;">
                    <el-button @click="chapterContentDialog = false">取消</el-button>
                    <el-button type="primary" @click="saveContent">确认</el-button>
                </div>
            </div>
        </div>
    </el-dialog>
</template>

<script>
export default {
    data() {
        return {
            page: 1,
            pageSize: 10,
            total: 0,
            loadingStatus: false,
            search: {
                name: null,
                isPay: null
            },
            dataList: [],
            bookDialog: false,
            book: {
                name: null,
                isPay: null,
                imageUrl: "",
                isHot: false,
                isShow: false,
                isPay: false,
                money: 0,
                discount: 10,
                sort: "",
                chapterList: []
            },
            bookRefRules: {
                name: [{ required: true, message: '必填' }],
                categoryId: [{ required: true, message: '必选' }],
            },
            imageUrl: "",
            bookChapterDialog: false,
            chapterContentDialog: false,
            content: {},
            selectChapter: {},
            selectTableRows: []
        }
    },
    created() {
        this.loadData()
    },
    methods: {
        handleUploadImage(event, insertImage, files) {
            try {
                let formData = new FormData();
                // 遍历当前临时文件List,将上传文件添加到FormData对象中
                files.forEach((item) => formData.append('file', item));

                // 调用后端接口,发送请求
                this.$axios.post('/file/upload?dir=mkdown', formData, {
                    // 因为我们上传了图片,因此需要单独执行请求头的Content-Type
                    headers: {
                        // 表示上传的是文件,而不是普通的表单数据
                        'Content-Type': 'multipart/form-data'
                    }
                }).then(({ data }) => {
                    if (data.code == 0) {
                        let fileMaps = data.originNames
                        let keys = Object.keys(fileMaps)
                        if (keys.length > 0) {
                            for (let index in keys) {
                                let key = keys[index]
                                let values = fileMaps[key]
                                // 此处只做示例
                                insertImage({
                                    url: values,
                                    desc: key,
                                    // width: 'auto',
                                    // height: 'auto',
                                });
                            }
                        }
                    }
                }).catch((err) => {
                    console.log(err, 'err');
                    this.$message.error("上传失败，请重试或者使用网络地址")
                })
            } catch (error) {
                console.log(error);
                this.$message.error("上传失败，请重试或者使用网络地址")
            }
        },
        handleSelectionChange(rows) {
            console.log(rows);
            this.selectTableRows = rows
        },
        saveChapter(item) {
            if (!item.name) {
                this.$message.error("不可为空")
                return
            }
            item.editStatus = false
            item.code = this.book.code
            this.$axios.post(`/book/saveChapter`, item).then(({ data }) => {
                if (data.code == 0) {
                    console.log(data.obj);
                    this.selectChapter = data.obj
                } else {
                    this.$message.error(data.msg)
                }
            })
        },
        removeChapter2(item, index) {
            if (item.id) {
                this.removeChapter(item, index)
            } else {
                this.book.chapterList.splice(index, 1)
            }
        },
        // 获取章节内容
        getChapterCotnent(item) {
            console.log(item);
            this.selectChapter = item
            this.$axios.get(`/book/getContent/${item.id}`).then(({ data }) => {
                if (data.code == 0) {
                    this.content = data.obj || {}
                } else {
                    this.$message.error(data.msg)
                }
            })
        },
        openChapterDialog(row) {
            this.$axios.get(`/book/getRowAndChapter/${row.id}`).then(({ data }) => {
                if (data.code == 0) {
                    if (!data.obj.platFrom) {
                        data.obj.system = []
                    }
                    this.book = data.obj
                    this.content = data.obj.content || {}
                    this.chapterContentDialog = true
                } else {
                    this.$message.error(data.msg)
                }
            })
        },
        async removeChapter(item, index) { // 需要删除章节及其内容
            this.$confirm("该操作无法撤回，确认删除该内容？", "确认", { type: 'error' }).then(() => {
                this.$axios.delete(`/book/removeChapter/${item.id}`).then(({ data }) => {
                    this.book.chapterList.splice(index, 1)
                })
            }).catch(() => {
                this.$message.info("已取消")
            })
        },
        addBookChapter() {
            this.book.chapterList.push({ editStatus: true })
        },
        loadData() {
            this.$axios.post(`/book/page/${this.page}/${this.pageSize}`, this.search).then(({ data }) => {
                if (data.code == 0) {
                    this.dataList = data.rows
                    this.total = data.total
                } else {
                    this.$message.error(data.msg)
                }
            }).catch(() => {
                this.$message.error("查询失败，请联系管理员！")
            })
        },
        getRowKey(row) {
            return row.id
        },
        resetSearch() {
            this.search = this.$options.data().search
            this.loadData()
        },
        selectLoadData() {
            this.search.isDelete = true
            this.loadData()
        },
        openBookAdd() {
            this.bookDialog = true
        },
        closeBookDialog() {
            this.$nextTick(() => {
                this.$refs.BookRef.resetFields()
                // this.$refs.BookRef.clearValidate()
                this.book = this.$options.data().book
            })
            this.bookDialog = false
        },
        closedBookDialog() {
            this.$nextTick(() => {
                this.$refs.BookRef.resetFields()
                // this.$refs.BookRef.clearValidate()
                this.book = this.$options.data().book
            })
        },
        saveBook() {
            this.loadingStatus = true
            this.$refs.BookRef.validate((validateor) => {
                if (validateor) {
                    this.$axios.post("/book/saveAndChapter", this.book).then(({ data }) => {
                        if (data.code == 0) {
                            this.loadData()
                        } else {
                            this.$message.error(data.msg)
                        }
                    })
                    this.dataList.push(this.book)
                    this.loadingStatus = false
                    this.closeBookDialog()
                } else {
                    this.loadingStatus = false
                }
            })
        },
        selectAndUpdate(row) {
            this.$axios.get(`/book/getRowAndChapter/${row.id}`).then(({ data }) => {
                if (data.code == 0) {
                    if (!data.obj.platFrom) {
                        data.obj.system = []
                    }
                    this.book = data.obj
                    this.bookDialog = true
                } else {
                    this.$message.error(data.msg)
                }
            })
        },
        selectChapterContent(row) {
            this.$axios.get(`/book/getContent/${row.id}`).then(({ data }) => {
                if (data.code == 0) {
                    if (!data.obj.platFrom) {
                        data.obj.system = []
                    }
                    this.book = data.obj
                    this.bookDialog = true
                } else {
                    this.$message.error(data.msg)
                }
            })
        },
        saveContent() {
            console.log(this.selectChapter)
            if (!this.content.content) {
                this.$message.error("无内容！")
                return
            }
            if (!this.selectChapter.id) {
                this.$message.error("请先选择章节！")
                return
            }
            this.content.chapterId = this.selectChapter.id
            console.log(this.content);
            this.$axios.post(`/book/saveContent/`, this.content).then(({ data }) => {
                if (data.code == 0) {
                    this.$message.success(data.msg)
                } else {
                    this.$message.error(data.msg)
                }
            })
        },
        exportWord() {
            if (this.selectTableRows.length <= 0) {
                this.$message.error("请选择需要导出的数据！")
                return
            }
            let ids = this.selectTableRows.map(x => x.id)
            console.log(ids);
            this.downLoad("http://localhost:8899/file/word/downLoadbookList", "XX分享.docx", "post", JSON.stringify(ids))
        },
        exportExcel() {
            this.downLoad("http://localhost:8899/excel/downLoadbookList", "XX分享.xlsx", "post")
        },
        downLoad(url, fileName, methodType = "get", params = null) {
            var xhr = new XMLHttpRequest()
            xhr.open(methodType, url)
            xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8'); //设置请求头(不同属性值传递的方式不同)
            xhr.responseType = 'blob'; //以blob的形式接收数据，一般文件内容比较大
            xhr.onload = function () {
                var content = this.response; //Blob数据
                var elink = document.createElement('a'); // 创建一个a标签用于下载
                elink.download = fileName; //规定被下载的超链接目标名字
                elink.style.display = 'none'; //标签隐藏
                var blob = new Blob([content]);
                elink.href = URL.createObjectURL(blob); //规定链接指向的页面的URL
                document.body.appendChild(elink);
                elink.click(); //原生dom触发
                document.body.removeChild(elink);
            };
            xhr.send(params); //post请求传的参数
        }
    }
}
</script>
<style scoped>
.el-dialog-div {
    height: 70vh;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}


/* // 滚动条宽度 */
.scopeCss::-webkit-scrollbar {
    width: 6px;
}

/* // 滚动条轨道 */
.scopeCss::-webkit-scrollbar-track {
    background: rgb(239, 239, 239);
    border-radius: 2px;
}

/* // 小滑块 */
.scopeCss::-webkit-scrollbar-thumb {
    background: #8ae77e3a;
    border-radius: 10px;
}

.scopeCss::-webkit-scrollbar-thumb:hover {
    background: #9fe77e;
}

.curos {
    cursor: pointer;
}

.curos:hover {
    background-color: #a2cddf7c;
}
</style>